package com.exthirteen.textgamescript.websocket;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * <p>
 * 公共Socket
 * </p>
 *
 * @author exthirteen
 * @since 2022/9/22
 */
@Slf4j
public abstract class CommonSocketClient {

    protected ApplicationContext applicationContext;

    /**
     * 客户端
     */
    @Getter
    protected final Client client;

    /**
     * 请求头
     */
    protected abstract Map<String,String> getWsHeaders();

    /**
     * 获取URL地址
     */
    protected abstract Supplier<String> getUrlSupplier();

    /**
     * 获取监听处理
     * @return 对消息的处理
     */
    protected abstract WebSocketClientListener getListener();

    /**
     * 在客户端被创建后及心跳之前的钩子函数
     * @return
     */
    protected Consumer<Client> beforeHeartbeatHandle(){
        return client -> {};
    }

    public CommonSocketClient(ApplicationContext applicationContext){
        this.applicationContext = applicationContext;
        this.client = WebSocketClientManager.initOne(
                //构建url的函数
                getUrlSupplier(),
                //设置请求头
                getWsHeaders(),
                //传入监听处理器
                getListener(),
                //在客户端被创建后及心跳之前的钩子函数
                beforeHeartbeatHandle());
    }

    /**
     * 关闭socket连接
     */
    public void close(){
        getClient().getSocketClient().close();
    }
}
